import { message } from 'antd'
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

export function debounce(func: any, delay = 500) {
  let timer: any

  return (...args: any[]) => {
    clearTimeout(timer)

    timer = setTimeout(function (this: any) {
      func.apply(this, args)
    }, delay)
  }
}

// 千位分割
export function formatWithRegex(number: number | string) {
  return !(number + '').includes('.')
    ? // 就是说1-3位后面一定要匹配3位
      (number + '').replace(/\d{1,3}(?=(\d{3})+$)/g, (match) => {
        return match + ','
      })
    : (number + '').replace(/\d{1,3}(?=(\d{3})+(\.))/g, (match) => {
        return match + ','
      })
}

export function fixedNumber(value: number, num?: number) {
  const numPow = Math.pow(10, num ?? 4)
  return Math.round(value * numPow) / numPow
}

export function tip(isShow: boolean = true, result: ComAPI.Result<any>) {
  if (result.code === 20000) {
    isShow && message.success(result.message)
    return true
  } else {
    message.error(result.message)
    return false
  }
}

export function handleEmptyList(data: { [key in any]: any }) {
  let newData = {}
  for (const [key, value] of Object.entries(data)) {
    newData = { ...newData, [key]: value ? value : null }
  }
  return newData
}

export function handleJsonToAscii(value: string) {
  const nonAsciiMap = new Map()
  nonAsciiMap.set('？'.charCodeAt(0), '?')
  nonAsciiMap.set('，'.charCodeAt(0), ',')
  nonAsciiMap.set('。'.charCodeAt(0), '.')
  nonAsciiMap.set('：'.charCodeAt(0), ':')
  nonAsciiMap.set('！'.charCodeAt(0), '!')
  nonAsciiMap.set('（'.charCodeAt(0), '(')
  nonAsciiMap.set('）'.charCodeAt(0), ')')
  nonAsciiMap.set('*'.charCodeAt(0), ' ') //42
  nonAsciiMap.set('   '.charCodeAt(0), ' ') //9
  const character = value.split('')
  let ascii = ''
  for (let i = 0; i < character.length; i++) {
    const code = Number(character[i].charCodeAt(0))
    if (isSpecialChar(code)) {
      if (nonAsciiMap.has(code)) {
        ascii += nonAsciiMap.get(code)
      }
    } else {
      ascii += character[i]
    }
  }

  function isSpecialChar(code: number) {
    if (code > 127 || code == 42 || code == 9) {
      return true
    } else {
      return false
    }
  }
  return ascii
}
